package com.jboltai.util.xinghuo;

import okhttp3.HttpUrl;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class XingHuoUtil {
    public static String getAuthUrl(String url, String apiKey, String apiSecret) {
        URL urlObj;
        try {
            urlObj = new URL(url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

        String host = urlObj.getHost();
        String date = sdf.format(new Date());
        String path = urlObj.getPath();

        String tmp = "host: %s\n" + "date: %s\n" + "GET %s HTTP/1.1";
        tmp = String.format(tmp, host, date, path);

        String sha;
        try {
            Mac mac = Mac.getInstance("hmacsha256");
            SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
            mac.init(spec);
            byte[] hexDigits = mac.doFinal(tmp.getBytes(StandardCharsets.UTF_8));
            // Base64加密
            sha = Base64.getEncoder().encodeToString(hexDigits);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + host + path)).newBuilder().addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).addQueryParameter("date", date).addQueryParameter("host", host).build();

        return httpUrl.toString();
    }
}
